package com.qf.lja.dao;

import com.qf.lja.enity.User;
import com.qf.lja.util.JDBCUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class UserDao {

    public List<User> userPage(int currenPage, int pageSize) {
        String sql = "select * from user limit ? , ?";
        int offset = (currenPage - 1) * pageSize;

        JDBCUtil jdbcUtil = new JDBCUtil();

        ResultSet rs = jdbcUtil.query(sql, offset, pageSize);
        List<User> list = new ArrayList<>();
        try {
            while (rs.next()) {//循环遍历所以行
                User user = convertToUser(rs);
                //省略其他属性
                list.add(user);
            }
        } catch (SQLException e) {
            System.out.println("sql执行失败！");
            e.printStackTrace();
        } finally {
            jdbcUtil.closeConnection();
        }
        return list;
    }

    public int countUser() {
        String sql = "select count(*) from user";


        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet rs = jdbcUtil.query(sql);

        int rows = 0;
        try {
            if (rs.next()) {
                rows = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            jdbcUtil.closeConnection();
        }
        return rows;
    }

    public List<User> queryAllUser(User condition) {
        String sql = "SELECT * FROM `user` WHERE 1=1";
        List<Object> params = new ArrayList<>();
        if (condition.getUserName() != null) {
            sql += " AND user_name LIKE CONCAT('%',?,'%')";
            params.add(condition.getUserName());
        }

        if (condition.getGender() != null) {
            sql += " AND gender = ?";
            params.add(condition.getGender());
        }
        JDBCUtil jdbcUtil = new JDBCUtil();
        System.out.println(sql);
        ResultSet rs = jdbcUtil.query(sql, params);
        List<User> list = new ArrayList<>();
//        System.out.println(rs.next() == true ? "rs : true" : "rs : false");
        try {
            while (rs.next()) {//循环遍历所以行
                User user = convertToUser(rs);
                //省略其他属性
                list.add(user);
            }
        } catch (SQLException e) {
            System.out.println("sql执行失败！");
            e.printStackTrace();
        } finally {
            jdbcUtil.closeConnection();
        }
        return list;
    }

    public List<User> queryAllUser() {
        String sql = "SELECT * FROM `user` WHERE 1=1";
        List<Object> params = new ArrayList<>();
        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet rs = jdbcUtil.query(sql);
        List<User> list = new ArrayList<>();
        try {
            while (rs.next()) {//循环遍历所以行
                User user = convertToUser(rs);
                //省略其他属性
                list.add(user);
            }
        } catch (SQLException e) {
            System.out.println("sql执行失败！");
            e.printStackTrace();
        } finally {
            jdbcUtil.closeConnection();
        }
        return list;
    }


    public User findByUsernameAndpasswd(String username, String password) {
        String sql = "SELECT * FROM user WHERE user_name = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet rs = jdbcUtil.query(sql, username);
        try {
            if (rs.next()) {
                String storedPassword = rs.getString("user_pass");
                if (verifyPassword(password, storedPassword)) { // 使用密码验证方法
                    User user = convertToUser(rs);
                    return user;
                } else {
                    return null;
                }
            }
        } catch (SQLException e) {
            System.out.println("sql执行失败！");
            e.printStackTrace();
        }
        return null;
    }


    public User findByUserId(int userid) {
        String Sql = "select * from user where user_id=?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet rs = jdbcUtil.query(Sql, userid);
        try {
            if (rs.next()) {
                return convertToUser(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private User convertToUser(ResultSet rs) {
        try {
            User user = new User();
            user.setUserId(rs.getInt("user_id"));
            user.setUserName(rs.getString("user_name"));
            user.setUserPass(rs.getString("user_pass"));
            user.setPhone(rs.getString("phone"));
            user.setEmail(rs.getString("email"));
            user.setGender(rs.getInt("gender"));
            user.setRole(rs.getInt("role"));
            user.setUserStatus(rs.getInt("user_status"));
            user.setCreatedTime(rs.getTimestamp("created_time"));
            user.setUpdatedTime(rs.getTimestamp("updated_time"));
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean adduser(String username, String password, String phone,
                           String email, int user_status, int role, int gender) {
        String sql = "INSERT INTO user " +
                "(user_name, user_pass, phone, email, user_status, role, gender, created_time, updated_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP())";
        String encryptedPassword = encryptPassword(password); // 使用MD5加密密码
        JDBCUtil jdbcUtil = new JDBCUtil();
        boolean success = jdbcUtil.insert(sql, username, encryptedPassword, phone, email, user_status, 1, gender);
        if (success) {
            System.out.println("用户添加成功！");
        } else {
            System.out.println("用户添加失败！");
        }
        return success;
    }

    private String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] encryptedPassword = md.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(encryptedPassword); // 使用Base64编码加密后的字节数据
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean verifyPassword(String inputPassword, String storedPassword) {
        String encryptedInputPassword = encryptPassword(inputPassword);
        return storedPassword.equals(encryptedInputPassword);
    }

    public boolean deleteUserById(int userId) {
        // 组织 SQL 删除语句
        String sql = "DELETE FROM user WHERE user_id = ?";

        // 调用 prepareUpdate 方法执行 SQL 删除操作
        JDBCUtil dbUtil = new JDBCUtil();
        boolean success = dbUtil.insert(sql, userId);

        // 检查是否成功删除数据
        if (success) {
            System.out.println("成功删除用户，用户ID：" + userId);
            return true;
        } else {
            System.out.println("删除用户失败，请检查控制台。");
            return false;
        }
    }

    public boolean update(int userId, String username, String password, String role, String state) {
        String sql = "UPDATE user SET username=?, password=?, role=?, state=? WHERE user_id=?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        int rs = jdbcUtil.update(sql, username, password, role, state, userId);
        if (rs != -1) {
            System.out.println("update success !!!!! ");
        } else {
            System.out.println("update error !!!");
        }
        return true;
    }

    public void updateInfo(Integer u_id, String name, String phone, String email) {
        String sql = "UPDATE user SET user_name=?, phone=?, email=? WHERE user_id=?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        jdbcUtil.update(sql, name, phone, email, u_id);
        jdbcUtil.closeConnection();
    }

    public void updateState(int i) {
        //不用参数每一次对数据库里面的statu字段取反
        String sql = "UPDATE user SET user_status = CASE user_status WHEN 0 THEN 1 ELSE 0 END WHERE user_id = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        jdbcUtil.update(sql, i);
        jdbcUtil.closeConnection();
    }
}






